package com.seeyon.apps.kk.manager;

import com.locknlock.sd.ifsd045.IFSD045_EA_SOServiceStub;
import com.locknlock.sd.ifsd045.IFSD045_EA_SOServiceStub.RETURN_type0;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.kk.utils.ValueUtils;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LockEaPricesManager extends BaseManager {
	private static final Log log = LogFactory.getLog(LockEaPricesManager.class);
	private FreemarkFlowManager freemarkFlowManager;

	public FreemarkFlowManager getFreemarkFlowManager() {
		return this.freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	public void addEaPricesForm(Long id) {
		String findallsql = this.freemarkFlowManager.fltTemplateIntoString("sql/sap/sendtosapsql/FIND_ALL_YCX.ftl",
				null);
		List<Map<String, Object>> queryForList = this.jdbcTemplate.queryForList(findallsql, id);
		for (Map<String, Object> map : queryForList) {
			this.addEaLog(map);
		}
		List<Map<String, Object>> list = new ArrayList<>();
		try {
			if (queryForList.size() <= 100) {
				// 抛送小于100条的数据
				this.sendToEa(queryForList);
			} else {
				// 拿到需要循环的次数
				int i = queryForList.size() / 100;
				if (queryForList.size() % 100 != 0) {
					i++;
				}
				System.out.println("i的长度是" + i);
				for (int k = 0; k < i; k++) {
					if (list.size() > 0) {
						list.clear();
					}
					System.out.println("i的值是" + i + "k的值是" + k);
					if (k + 1 < i) {
						for (int f = k * 100; f < (k + 1) * 100; f++) {
							System.out.println("f的长度是" + f);
							list.add(queryForList.get(f));
						}
					} else {
						for (int f = k * 100; f < queryForList.size(); f++) {
							System.out.println("f的长度是" + f);
							list.add(queryForList.get(f));
						}
					}
					this.sendToEa(list);
				}
			}
			for (Map<String, Object> map : queryForList) {
				this.UpdateLog(map);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public List<Map<String, Object>> sendToEa(List<Map<String, Object>> list) throws RemoteException {
		if (!list.isEmpty()) {
			IFSD045_EA_SOServiceStub stub = new  IFSD045_EA_SOServiceStub();
			ServiceClient client = stub._getServiceClient();
			org.apache.axis2.client.Options options = client.getOptions();
			options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, true);
			options.setManageSession(true);
			client.cleanupTransport();
			HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
			auth.setUsername("IFPO01");
			auth.setPassword("Passpo1$");
			stub._getServiceClient().getOptions().setProperty("_NTLM_DIGEST_BASIC_AUTHENTICATION_", auth);
			IFSD045_EA_SOServiceStub.IFSD045_EA_REQ_MT iFSD045_EA_REQ_MT0 = new IFSD045_EA_SOServiceStub.IFSD045_EA_REQ_MT();
			IFSD045_EA_SOServiceStub.IFSD045_EA_REQ_DT param = new IFSD045_EA_SOServiceStub.IFSD045_EA_REQ_DT();
			IFSD045_EA_SOServiceStub.Row_type0[] rt = new IFSD045_EA_SOServiceStub.Row_type0[list.size()];
			int num=0;
			for (Map<String, Object> map : list) {
				IFSD045_EA_SOServiceStub.Row_type0 rrt = new IFSD045_EA_SOServiceStub.Row_type0();
				rrt.setZSERL(MapUtils.getString(map, "订单编号"));
				rrt.setZPTYPE("1");
				rrt.setVKORG(MapUtils.getString(map, "营业组织"));
				rrt.setKUNNR(MapUtils.getString(map, "客户编号"));
				rrt.setMATNR(MapUtils.getString(map, "物料代码"));
				rrt.setDATAB(MapUtils.getString(map, "开始日期"));
				rrt.setDATBI(MapUtils.getString(map, "结束日期"));
				rrt.setZNETPR2(MapUtils.getString(map, "供货价"));
				Date ifdate = new Date();
				String ifdate1 = DateFormatUtils.format(ifdate, "yyyyMMdd");
				rrt.setIF_DATE(ifdate1);
				rrt.setKWMENG(MapUtils.getString(map, "数量"));
				rrt.setZTITLE(MapUtils.getString(map, "标题"));
				rrt.setVKBUR(MapUtils.getString(map, "营业部门"));
				rt[num++] = rrt;
			}
			param.setRow(rt);
			iFSD045_EA_REQ_MT0.setIFSD045_EA_REQ_MT(param);
			IFSD045_EA_SOServiceStub.IFSD045_EA_RES_MT ifsd045_EA_SO = stub.IFSD045_EA_SO(iFSD045_EA_REQ_MT0);
				IFSD045_EA_SOServiceStub.RETURN_type0[] return1 = ifsd045_EA_SO.getIFSD045_EA_RES_MT().getRETURN();
				for (int i = 0; i < list.size(); i++) {
					Map<String,Object>map=list.get(i);
				map.put("XIAOXI", return1[i].getMESSAGE());
				map.put("STATUS", return1[i].getSTATUS());
				log.info(return1[i].getMESSAGE()+""+return1[i].getSTATUS()+""+return1[i].getDATAB()+""+
						return1[i].getDATBI()+""+return1[i].getKUNNR()+""+return1[i].getMATNR()+""+
						return1[i].getVKORG()+""+return1[i].getZPTYPE()+""+return1[i].getZSERL());
				}
		}
		return list;

	}

	/**
	 * for (int s=0; s<return1.length; s++) { Map<String,Object> mv=new HashMap<>();
	 * mv.put("MESSAGE", return1[s].getMESSAGE()); mv.put("STATUS",
	 * return1[s].getSTATUS()); list.add(mv);
	 * System.out.println("返回消息"+return1[s].getMESSAGE());
	 * System.out.println("返回状态"+return1[s].getSTATUS()); }
	 * 
	 * @param map
	 */
	public void addEaLog(Map<String, Object> map) {
		map.put("types", "价格起案(一次性活动)");// 推送类型
		String selectYsj = this.freemarkFlowManager.fltTemplateIntoString("sql/sap/ealog/chongxinps.ftl", map);
		map.put("source", selectYsj);// 推送源数据
		map.put("agin", ValueUtils.getConfig().getLong("kk.CXCS"));// 是否重新传输
		long mostSignificantBits = UUID.randomUUID().getMostSignificantBits();
		map.put("SUIJI",mostSignificantBits);
		// 生成新的日志记录
		String dataXml = this.freemarkFlowManager.fltTemplateIntoString("sql/sap/ealog/EALOG.ftl", map); // memberDay可以直接给
		// 可以使用数据模板生成，这样底表事件依然有效
		FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
		try {
			FormExport[] formExportData = FormUtils.xmlTransformFormExports(dataXml);
			for (FormExport formExport : formExportData) {
				formFactory.importBusinessFormData("admin1", "LK_SAPLOG_51", formExport, null);
			}
		} catch (Exception e) {
			log.error(e);
		}
	}
	
	public void UpdateLog(Map<String, Object> map) {
		Map<String,Object> msp = new HashMap<>();
		msp.put("STATUS", MapUtils.getString(map, "STATUS"));
		msp.put("MESSAGER", MapUtils.getString(map, "XIAOXI"));
		msp.put("SUI", MapUtils.getString(map, "SUIJI"));
		String updatesql = this.freemarkFlowManager.fltTemplateIntoString("sql/sap/ealog/gengxin.ftl", msp);
		this.jdbcTemplate.update(updatesql);
	}
	
}